package mobile.android.portal.ui;

import java.net.ConnectException;

import org.w3c.dom.Text;

import mobile.android.portal.R;
import mobile.android.portal.obj.ProductByProductId;
import mobile.android.portal.webservice.BusinessPortalWebService;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class SearchResultActivity extends Activity{
	
	// initializing GUI COMPONENTS
	TextView resultProductName;
	TextView resutlCategoryName;
	TextView resultManufacturerName;
	TextView resultPrice;
	TextView resultQuantity;
	TextView resultCntTextView;
	
	
	/* Variable to store the id of the selected product */
	public static int selectedProductId;
	public static String selecctedCategoryName;
	
	ProductByProductId productByProductId;
	
	ProgressDialog progressDialog;
	
	Handler productByProductIdHandler;
	int resultCount;
	//int selectedProductId;
		
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_search_results);
        
        resultProductName = (TextView) findViewById(R.id.resultNameTextView);
        resutlCategoryName = (TextView) findViewById(R.id.resultCategoryTextView);
        resultManufacturerName = (TextView) findViewById(R.id.resultManuTextView);
        resultPrice = (TextView) findViewById(R.id.resutlPriceTextView);
        resultQuantity = (TextView) findViewById(R.id.resutlQuantityTextView);
        resultCntTextView = (TextView) findViewById(R.id.resultCountTextView);
        
        
        selectedProductId = Integer.parseInt(getIntent().getExtras().getString("product_id"));
        selecctedCategoryName = getIntent().getExtras().getString("category_name");
        
        progressDialog = mobile.android.portal.util.Functions.getProgressDialog(this, "Please wait...");
        
        /* Calls the web service to get product info */
		new WSGetProductByProductId().execute(null, null, null);

		productByProductIdHandler = new Handler() {
			
			public void handleMessage(Message message) {
				
				/*
				 *  If the response message is not an empty message display the output. Otherwise display 
				 * alert dialog which contains the error message.
				 *  */
				if (message.what != -1) {
					resultCount = productByProductId.getCount();
					
					Log.v("resultCCN", Integer.toString(resultCount));
					
					/*
					 *  If no information available set GUI components invisible and display information 
					 * not available toast message. Otherwise display the post office information.
					 *  */
					if (productByProductId.getCount() <= 0) {
						Toast noInfomationToastMesage = Toast.makeText(SearchResultActivity.this, "No information available ", Toast.LENGTH_LONG);
						noInfomationToastMesage.show();
						
						progressDialog.dismiss();
					} else {
						
						//resultTitle.setVisibility(View.VISIBLE);
						
						resultProductName.setVisibility(View.VISIBLE);
						resultManufacturerName.setVisibility(View.VISIBLE);
						resultPrice.setVisibility(View.VISIBLE);
						resultQuantity.setVisibility(View.VISIBLE);
						resutlCategoryName.setVisibility(View.VISIBLE);
						resultCntTextView.setVisibility(View.VISIBLE);
						
						String product_name = productByProductId.getProductNames()[0];
						String category_name = selecctedCategoryName;
								
						String price = productByProductId.getPrices()[0];
						String quantity = productByProductId.getQuantities()[0];
						
						resultCntTextView.setText(Integer.toString(resultCount)+ " Results Found");
						
						if (!product_name.equals("anyType{}")) {
							resultProductName.setText(product_name);
						} else {

							resultProductName.setText(null);
						}
						
						if (!category_name.equals("anyType{}")) {
							resutlCategoryName.setText(category_name);
						} else {

							resutlCategoryName.setText(null);
						}
						
						if (!price.equals("anyType{}")) {
							resultPrice.setText(price);
						} else {

							resultPrice.setText(null);
						}
						
						if (!quantity.equals("anyType{}")) {
							resultQuantity.setText(quantity);
						} else {

							resultQuantity.setText(null);
						}
						
						resultManufacturerName.setText("Manufacturer " + Math.round(Math.random()*10));					
						progressDialog.dismiss();
					}
					
				}
			}
		};
    }
	
	public void onOrderButtonClick(View v) {
    	Intent placeOrderScreen = new Intent(this, PlaceOrderActivity.class);
    	
    	placeOrderScreen.putExtra("product_name", resultProductName.getText());
    	placeOrderScreen.putExtra("category_name", resutlCategoryName.getText());
    	
    	startActivity(placeOrderScreen);
	}
	
	/*
	 * Asynchronous back ground process to retrieve the post offices of the
	 * selected division. If an exception occurred sends and empty message to
	 * the web service client
	 */
	class WSGetProductByProductId extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... params) {
			try {
				productByProductId = BusinessPortalWebService.getProductByProductId(selectedProductId);
				productByProductIdHandler.sendMessage(productByProductIdHandler.obtainMessage());
				return null;

			} catch (ConnectException e) {
				// TODO: handle exception
				// Send an empty message if an ConnectException occurred
				productByProductIdHandler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("ConnectException", "ConnectException occured");
				e.printStackTrace();

			} catch (Exception e) {
				// TODO: handle exception
				// Send an empty message if an exception occurred
				productByProductIdHandler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("Exception", "Exception occured");
				e.printStackTrace();
			}
			return null;
		}
	}
}
